package cn.khson.vrd.controller;

import cn.khson.vrd.entity.User;
import cn.khson.vrd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    private UserMapper mapper;

    @RequestMapping("/login")
    public int login(User user, String rem, HttpServletResponse response,HttpSession session){
        User u = mapper.selectByUserName(user.getUsername());
        if(u!=null){
            if(u.getPassword().equals(user.getPassword())){
                session.setAttribute("user",u);
                if(rem!=null){//rem 代表记住密码复选框
                    //创建Cookie对象
                    Cookie cookie = new Cookie("username",user.getUsername());
                    Cookie cookie2 = new Cookie("password",user.getPassword());
                    //设置保存时间,单位秒
                    cookie.setMaxAge(60*60*24*30);
                    cookie2.setMaxAge(60*60*24*30);
                    //通过response对象将Cookie下发给客户端
                    response.addCookie(cookie);
                    response.addCookie(cookie2);
                }
                return 1;//登录成功
            }else {
                return 2;//密码错误
            }
        }
        return 3;//用户不存在
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

    @RequestMapping("/checkLogin")
    public boolean cherckLogin(HttpSession session){
        User u = (User)session.getAttribute("user");
        return u!=null;
    }

    @RequestMapping("/currentuser")
    public User currentuser(HttpSession session){
        //取出登录成功时,保存的User对象
        User user = (User)session.getAttribute("user");
        //如果user 为null,前端response.data获取的是""
        return user;
    }
}
